﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace System.Windows.Controls
{
    /// <summary>
    /// Implements a simple, theme-aware and animated progress control
    /// </summary>
    [TemplateVisualState(Name="Running", GroupName="CommonStates")]
    [TemplateVisualState(Name="NotRunning", GroupName="CommonStates")]
    public class ControlProgress : ControlBase
    {
        /// <summary>
        /// Initializes a <see cref="ControlProgress"/> instance.
        /// </summary>
        public ControlProgress()
        {
            this.DefaultStyleKey = typeof(ControlProgress);
            this.IsHitTestVisible = false;
            this.Width = this.Height = DEF_SIZE;
        }

        private bool    _Active = false;
        private const   double DEF_SIZE = 64;

        /// <summary>
        /// Gets a boolean value indicating whether the progress control is currently active
        /// </summary>
        public bool Active
        {
            get { return _Active; }
        }

        /// <summary>
        /// (Override) Called when the template is applied to the control.
        /// </summary>
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            GoToState(true, "NotRunning");
        }

        /// <summary>
        /// Shows the progress control - this sets the visibility and sets the Visual state to "Running".
        /// </summary>
        public void Show()
        {
            if (this.Visibility == Visibility.Collapsed) this.Visibility = Visibility.Visible;

            if (this.Parent != null && this.Parent is FrameworkElement)
            {
                FrameworkElement element = (FrameworkElement)this.Parent;
                LayoutHelper.SetVisualLocation(this, (element.ActualWidth - DEF_SIZE) / 2, (element.ActualHeight - DEF_SIZE) / 2);
                this.Width = DEF_SIZE;
                this.Height = DEF_SIZE;
                this.Arrange(new Rect((element.ActualWidth - DEF_SIZE) / 2, (element.ActualHeight - DEF_SIZE) / 2, DEF_SIZE, DEF_SIZE));
            }

            _Active = GoToState(true, "Running");
        }

        /// <summary>
        /// Hides the control and sets the state to "NotRunning"
        /// </summary>
        public void Hide()
        {
            _Active = !GoToState(true, "NotRunning");
        }
    }
}
